{% extends 'admin_dashboard.html' %}
{% block content %}
<div class="card">
  <h2>{{ '编辑客户' if customer else '添加客户' }}</h2>
  <form method="post" id="addForm" class="form">
    <div class="form-group">
      <label>姓名</label>
      <input type="text" name="customerName" value="{{ customer.customerName if customer }}" required>
    </div>
    <div class="form-group">
      <label>身份证号</label>
      <input type="text" name="PID" value="{{ customer.PID if customer }}" required>
    </div>
    <div class="form-group">
      <label>电话</label>
      <input type="text" name="telephone" value="{{ customer.telephone if customer }}" required>
    </div>
    <div class="form-group">
      <label>地址</label>
      <input type="text" name="address" value="{{ customer.address if customer }}">
    </div>
    <div class="form-actions">
      <button type="submit" class="btn primary">提交</button>
      <a href="{{ url_for('customers') }}" class="btn">取消</a>
    </div>
  </form>
</div>
<script>
document.getElementById('addForm').addEventListener('submit', function (e) {
  e.preventDefault();

  const formData = new FormData(this);
  const urlParams = new URLSearchParams(window.location.search);
  const nextParam = urlParams.get('next') || '/customers';

  fetch(`/customers/add?next=${encodeURIComponent(nextParam)}`, {
    method: 'POST',
    body: formData
  })
  .then(res => res.json())
  .then(data => {
    if (data.success) {
      let message = '✅ 客户添加成功！';

      if (data.next && data.next.includes('/cards/add')) {
        message += '\n🎉 已自动为其开通银行卡！\n' +
                   '卡号：' + data.cardID + '\n' +
                   '初始余额：' + data.balance + ' 元\n' +
                   '密码：' + data.pass + '\n' +
                   '存款类型：' + data.savingID + '（活期）';
      }

      alert(message);
      window.location.href = data.next || '/customers';

    } else {
      alert('❌ ' + data.message);
    }
  })
  .catch(error => {
    alert('⚠️ 提交失败，请稍后再试。');
    console.error(error);
  });
});
</script>

{% endblock %}
